package org.blackcat.service.impl;

import org.blackcat.common.DESUtil;
import org.blackcat.common.DateUtils;
import org.blackcat.common.StringUtils;
import org.blackcat.common.UUIDUtils;
import org.blackcat.core.annotation.Validation;
import org.blackcat.dao.TemperatureDao;
import org.blackcat.dao.redis.RedisHandle;
import org.blackcat.domain.Temperature;
import org.blackcat.domain.common.MsgResponse;
import org.blackcat.domain.enums.DateEnum;
import org.blackcat.domain.enums.ResponseCodeEnum;
import org.blackcat.domain.enums.UserEnum;
import org.blackcat.service.TemperatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 詹泽
 * @date 2017/2/22
 */
@Service
public class TemperatureServiceImpl implements TemperatureService{

    @Autowired
    private TemperatureDao temperatureDao;

    @Autowired
    private RedisHandle redisHandle;

    @Override
    @Validation
    public MsgResponse<Object> addTemerature(Temperature temperature,String token) throws Exception {
        String userIdAES = redisHandle.getString(token);
        String userId = DESUtil.aesDecrypt(userIdAES,UserEnum.USER_AES_KEY.getValue());
        temperature.setId(UUIDUtils.uuid());
        temperature.setUserId(userId);
        temperature.setGmtCreate(new Date());
        temperature.setGmtModified(new Date());
        Integer rs = temperatureDao.addTemerature(temperature);
        if(rs != null && rs > 0){
            return new MsgResponse<>(ResponseCodeEnum.SUCCESS);
        }
        return new MsgResponse<>(ResponseCodeEnum.EXCEPTION);
    }

    @Override
    public MsgResponse<List<Temperature>> listTemerature(String date,int status, String token) throws Exception {
        String userIdAES = redisHandle.getString(token);
        String userId = DESUtil.aesDecrypt(userIdAES, UserEnum.USER_AES_KEY.getValue());
        if(!(StringUtils.regularMatch(date,"\\d{1,2}(-\\d{1,2})?"))){
            return new MsgResponse<>(ResponseCodeEnum.REQUEST_PARAMETER_ERROR);
        }
        if(status == DateEnum.MONTH.getCode()){
            String minDateStr = DateUtils.getCalendar(Calendar.YEAR)+"-"+date+"-"+"01";
            String maxDateStr = DateUtils.getCalendar(Calendar.YEAR)+"-"+date+"-"+DateUtils.getMaxDayByMonth(minDateStr);
            List<Temperature> list = temperatureDao.listTemperature(userId,minDateStr,maxDateStr);
            return new MsgResponse<>(ResponseCodeEnum.SUCCESS,list);
        }
        String minDateStr = DateUtils.getCalendar(Calendar.YEAR)+"-"+date+" "+"00:00:00";
        String maxDateStr = DateUtils.getCalendar(Calendar.YEAR)+"-"+date+" "+"23:59:59";
        List<Temperature> list = temperatureDao.listTemperature(userId,minDateStr,maxDateStr);
        return new MsgResponse<>(ResponseCodeEnum.SUCCESS,list);
    }
}
